﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Domain.Enums;
using QMERP.Infrastructure.CustomException;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Extensions;
using QMERP.Infrastructure.Tools;

namespace QMERP.Application.Services
{
    public class RoleService : IRoleService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly QMERPDbContext _db;
        public RoleService(IMapper mapper, QMERPDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<List<RoleResponse>> GetBasicRoles(long[] ids)
        {
            var query = _db.Role.Where(x => x.Id != ConfigurationUtils.GetSection("DefaultRoleId").ToInt());
            if (ids.Length > 0)
            {
                query = query.OrderByDescending(o => ids.Contains(o.Id));
            }
            var roles = await query.ToListAsync();
            return _mapper.Map<List<RoleResponse>>(roles);
        }
        /// <summary>
        /// 角色视图
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageResponse<RoleResponse>> Query(PageRequest<RoleRequest> request)
        {
            var response = new PageResponse<RoleResponse>();

            var query = Where(request);

            var list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            response.TotalCount = await query.CountAsync();
            response.PageIndex = request.PageIndex;
            response.PageSize = request.PageSize;
            response.List = _mapper.Map<List<RoleResponse>>(list);
            return response;
        }
        /// <summary>
        /// 获取id的角色详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RoleResponse> Detail(long id)
        {
            var model = await _db.Role.FindByIdAsync(id);
            return _mapper.Map<RoleResponse>(model);
        }
        /// <summary>
        /// 角色保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(RoleSaveRequest request)
        {
            if (_db.Role.Any(x => x.Name.ToLower() == request.Name && x.Id != request.Id))
                throw new ApiException("角色名称已存在!");
            if (request.Id == null)
            {
                Role model = _mapper.Map<Role>(request);
                await _db.Role.AddAsync(model);
            }
            else
            {
                Role? model = await _db.Role.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("角色不存在!");
                model.Name = request.Name;
                model.Remark = request.Remark;
            }
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 角色删除(假删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Remove(long[] ids)
        {
            if (ids.Length<=0)
                throw new ApiException("id不能为空!");
            if (ids.Contains(ConfigurationUtils.GetSection("AdminRoleId").ToInt()))
                throw new ApiException($"超级管理员角色不允许删除!");
            if (ids.Contains(ConfigurationUtils.GetSection("DefaultRoleId").ToInt()))
                throw new ApiException($"默认用户角色不允许删除!");

            var roleNames = await _db.Role.Include(x => x.Organization_Roles).Include(x => x.User_Roles).Where(x => ids.Contains(x.Id) && (x.Organization_Roles.Count > 0 || x.User_Roles.Count > 0 )).Select(s => s.Name).ToListAsync();

            if (roleNames.Count > 0)
            {
                throw new ApiException($"角色:{string.Join(',', roleNames)}已被绑定,不允许删除!");
            }

            await _db.Role.RemoveAsync(ids.ToArray());
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 绑定角色
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task BindRoles(BindRolesRequest request)
        {
            var master = request.Master.GetEnum<RoleMasterEnum>();
            if (master == RoleMasterEnum.User)
            {
                var model = await _db.User.Include(x => x.User_Roles).FindByIdAsync(request.Id) ?? throw new ApiException("用户不存在!");
                //删除角色列表(除了默认用户角色)
                model.User_Roles = model.User_Roles.Where(x => x.RoleId == ConfigurationUtils.GetSection("DefaultRoleId").ToInt()).ToList();
                if (request.RoleIds != null)
                {
                    foreach (long roleId in request.RoleIds)
                    {
                        User_Role role_User = new()
                        {
                            RoleId = roleId,
                        };
                        model.User_Roles.Add(role_User);
                    }
                }
            }
            else if (master == RoleMasterEnum.Organization)
            {
                var model = await _db.Organization.Include(x => x.Organization_Roles).FindByIdAsync(request.Id) ?? throw new ApiException("组织机构不存在!");
                //删除角色列表
                _db.RemoveRange(model.Organization_Roles);
                if (request.RoleIds != null)
                {
                    foreach (long roleId in request.RoleIds)
                    {
                        Organization_Role role_Organization = new()
                        {
                            RoleId = roleId,
                        };
                        model.Organization_Roles.Add(role_Organization);
                    }
                }
            }
            
            await _db.SaveChangesAsync();
        }
        private IQueryable<Role> Where(PageRequest<RoleRequest> request)
        {
            IQueryable<Role> query = _db.Role.AsNoTracking();
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query.OrderByDescending(x => x.CreatedOn);
        }
    }
}
